package cn.coco.jf.fw.admin.config;

import java.util.List;

import org.apache.log4j.Logger;

import cn.coco.jf.fw.admin.model.JkUser;
import cn.exlu.coco.core.exception.CoCoRuntimeException;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;



public class AdminInterceptor implements Interceptor{
    private static Logger _LOG = Logger.getLogger(AdminInterceptor.class);
 
    @Override
    public void intercept(Invocation inv) {
        final JkUser jkUser = (JkUser)inv.getController().getSessionAttr("jkUser");

        if(jkUser == null){
           inv.getController().redirect("/login");
        }else{
            List<String> menus = jkUser.getMenus();
            
            if(!menus.contains(inv.getControllerKey())){
                inv.getController().renderError(601);
                return;
            }

            try{
                inv.invoke();
            }catch(Exception e){
                _LOG.error("系统异常：", e);
                // 如果返回的是JSON数据
                // 判断依据是方法名以do开头
                String methodName = inv.getMethodName();
                if(methodName.startsWith("do")){
                	// TODO 应该改成 inv.getController().renderError(XXX); 然后设置返回JsonRender 
                    inv.getController().removeAttr("contentPath");
                    inv.getController().setAttr("code", 500);
                    inv.getController().setAttr("msg", "发生系统异常");
                    inv.getController().renderJson();
                }else{
                    // 抛出异常，用于ActionHandle捕获
                    _LOG.error("系统异常", e);
                    throw new CoCoRuntimeException("系统异常");
                }
               
            }
            
        }
            
        
    }

}
